<template>
    <div>
        <div class="content">
            <el-button type="primary" size="mini" @click="handleButton('add')">新增录入</el-button>
            <el-button size="mini" @click="handleButton('close')">关闭</el-button>
            <el-button size="mini" @click="handleButton('delete')">删除</el-button>
            <el-button size="mini" @click="handleButton('primary-search')">高级查询</el-button>
            <el-button size="mini" @click="handleButton('loadout')">导出</el-button>
            <el-button size="mini" @click="handleButton('doLayout')"> 布局设置</el-button>
            <el-button size="mini" @click="handleButton('refresh')"> 刷新</el-button>
        </div>
        <div class="noOpened">
            <RiskTableP
                :ref="'risk-table-' + type"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="showColumns"
                :paging="paging"
                v-loading="tableLoading"
                @page-change="getTableData"
                @checkRowKeys-change="checkRowKeysChangeEmit"
                :key="tableKey"
            >
                <template #prohibitionDate="{ row }">
                    <el-tag size="mini" :class="handleTagStyle(row.prohibitionDate)" v-if="row.prohibitionDate !== undefined">{{
                        row.prohibitionDate
                    }}</el-tag>
                    <span v-else> -- </span>
                </template>
                <template #insideDays="{ row }">
                    <el-tag style="background-color: #02a7f0; color: #fff; width: 35px;text-align:center" size="mini">{{
                        row.insideDays || 0
                    }}</el-tag>
                </template>
                <!-- <template #detail="{ row }">
                    <a href="javascript:;" @click="handleBtnRow('look', row)">详情</a>
                </template> -->
                <template #operation="{ row }">
                    <a href="javascript:;" @click="handleBtnRow('follow-manage', row)">跟踪管理</a>
                    <a href="javascript:;" @click="handleBtnRow('look', row)">查看</a>
                    <a href="javascript:;" @click="handleFeedback('look', row)">调整方案</a>
                </template>
            </RiskTableP>
        </div>
        <!-- 布局设置 -->
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="layoutTableName"
            :visible.sync="layoutDialog"
            :column="tableColumns"
            :fixedColumns="fixedColumns"
        />
        <!-- 高级查询 -->
        <TransfinitePrimarySearch
            type="manual"
            :searchParam="searchParam"
            :visible="primarySearchVisible"
            @handleButton="handleButton($event.type, $event.params)"
        ></TransfinitePrimarySearch>

        <!-- 事件处理、新增跟踪记录 -->
        <ManualEventRecord
            v-if="eventRecordVisible"
            :visible.sync="eventRecordVisible"
            :type="eventRecordType"
            :overrunDetail="currentManual"
            @initEventRecord="handleInitEventRecord"
        />

        <!-- 事件处理 -->
        <EventFeedback v-if="visible" :visible.sync="visible" type="look" :overrunDetail="currentOverrun" />

        <!-- 关闭弹框 -->
        <yh-dialog title="超限指标关闭" :visible.sync="closeVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="600px" drag>
            关闭原因：
            <el-input type="textarea" :rows="6" v-model="closeReason" size="mini"></el-input>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeVisible = false"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="handleButton('close-confirm')"> 确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Watch } from 'vue-property-decorator';
import { TransfiniteIndicator } from '../../class/transfinite-Indicator';
import API from '../../api/manual-processing';
import { ColumnVO, TableConfigVO, VueObject } from '@/common/vo';
import TransfinitePrimarySearch from '../transfinite-Indicator/transfinite-primary-search.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import ManualEventRecord from './manual-event-record.vue';
import EventFeedback from '../../disposal-center/event-feedback.vue';
import { ManualEventRepVO } from '../../vo/manual-processing';
import { TransfiniteIndicatorDetailDTO } from '../../vo/transfinite-Indicator';
import Dict from '../../dict/index';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'ManualManage',
    components: { RiskTableLayout, RiskTableP, TransfinitePrimarySearch, RiskIconButton, ManualEventRecord, EventFeedback },
})
export default class ManualManage extends TransfiniteIndicator {
    @Prop() activeValue: string;
    type: string = 'manual-manage';
    tableData: any = [];

    tableColumns: ColumnVO[] = this.columnUtil.transfiniteCheckManualTableColumns;

    tableConfig: TableConfigVO = {
        rowKey: 'overrunEventId',
    };
    Dict = new Dict();
    fixedColumns: any[] = [
        { title: '事件编号', field: 'overrunEventId', width: '80px', fixed: 'left' },
        { title: '事件状态', field: 'eventStatus', minWidth: '100px', render: value => Dict.eventStatusPojo[value], fixed: 'left' }, // 0-未发起1-调整中2-已关闭
        {
            title: '反馈情况',
            field: 'feedbackStatus',
            minWidth: '100px',
            render: value => Dict.feedbackStatusPojo[value],
            fixed: 'left',
        }, // 0-待反馈1-已反馈
        { field: 'operation', fixed: 'right', title: '操作', align: 'center', width: '150px' },
    ];

    layoutTableName: string = 'TN_TRANSFINITE_MANUAL_MANAGE';

    requestTableMethodName: any = API.transfiniteIndicatorDetailManualList;

    loadOutRequestName: any = API.downLoadFileTransfiniteManual;

    eventRecordVisible: boolean = false; // 事件记录
    eventRecordType: string = ''; // add | look | follow
    currentManual: ManualEventRepVO = {
        overrunEventId: 0,
        fundProductCode: [],
        thresholdValue: '',
        compareType: '',
        result: 0,
        prohibitionDate: 0,
        entryName: '',
        lastAdjustDate: '',
        articeInfo: '',
        clauseCode: '',
        tradeDate: '',
        investmentManager: '',
        triggerType: '',
        approveDate: '',
    };

    visible: boolean = false;
    currentOverrun: any = {};

    primarySearchVisible: boolean = false;

    searchParam: TransfiniteIndicatorDetailDTO = {
        eventStatusList: [],
        triggerType: [],
        adjustProgerss: [],
        fundCode: [],
        investmentManager: [],
        tradeDate: '',
        prohibitionDateUnit: '',
        prohibitionDate: '',
        feedbackStatus: '',
        articeInfo: '',
    };

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'manual-manage' && this.$attrs.echartParams['isClick']) {
            if (this.isFirst) {
                this.getTableData();
                this.isFirst = false;
            }
        }
    }

    // TODO
    @Watch('$attrs.echartParams', { deep: true, immediate: true })
    handleEchartParams() {
        const echartParams: any = this.$attrs.echartParams;
        console.log(echartParams, 'echartParams');
        if (this.activeValue === 'manual-manage' && !echartParams.isClick) {
            const keys = Object.keys(this.searchParam);
            for (let key of keys) {
                this.searchParam[key] = echartParams.params[key] || '';
            }
            this.getTableData();
        }
    }

    mounted() {
        // this.$watch(
        //     () => {
        //         return this.$attrs.echartParams;
        //     },
        //     val => {
        //         const echartParams: any = this.$attrs.echartParams;
        //         console.log(echartParams, 'echartParams');
        //         if (this.activeValue === 'manual-manage' && !echartParams.isClick) {
        //             const keys = Object.keys(this.searchParam);
        //             for (let key of keys) {
        //                 this.searchParam[key] = echartParams.params[key] || '';
        //             }
        //             this.getTableData();
        //         }
        //     }
        // );
        // 监听布局设置
        super.watchShowColumns();
    }

    getTableData() {
        return super.getTableData();
    }

    /**
     * 操作行
     */
    async handleButton(type: string, data?: any) {
        //     if (type == 'close' || type == 'delete') {
        //     let name = '';
        //     let requestName;
        //     if (type == 'close') {
        //         name = '关闭';
        //         requestName = TransfiniteAPI.reportClose;
        //     } else if (type == 'delete') {
        //         name = '删除';
        //         requestName = TransfiniteAPI.reportDelete;
        //     }
        //     const checkRowKeys = (this.$refs['risk-table-manual-manage'] as VueObject).checkRowKeys;
        //     if (checkRowKeys.length < 1) {
        //         this.yh_message_info(`请先勾选需${name}的数据！`);
        //         return;
        //     }
        //     requestName({ overrunEventIds: checkRowKeys }).then(() => {
        //         this.yh_message_success(name + '成功');
        //         this.paging.currentPage = 1;
        //         super.getTableData();
        //         // 清除导出时列表勾选项
        //         this.$nextTick(() => {
        //             (this.$refs['risk-table-' + this.type] as any).resetCheckRowKeys();
        //         });
        //     });
        // } else
        if (type == 'add') {
            this.eventRecordVisible = true;
            this.eventRecordType = type;
        } else if (type == 'primary-search') {
            this.primarySearchVisible = true;
        } else if (type == 'primary-search-confirm') {
            this.primarySearchVisible = false;
            this.searchParam = JSON.parse(JSON.stringify(data));
            this.paging.currentPage = 1;
            await super.getTableData();
        } else if (type == 'primary-search-cancel') {
            this.primarySearchVisible = false;
            // 点击取消或者X掉时恢复默认值
        } else {
            super.handleButtonEmit(type);
        }
    }

    checkRowKeysChangeEmit(keys) {
        super.checkRowKeysChangeEmit(keys);
    }

    // 查看行
    handleBtnRow(type: string, row: any) {
        this.currentManual = JSON.parse(JSON.stringify(row));
        this.eventRecordType = type;
        this.eventRecordVisible = true;
    }

    /**
     * 调整方案
     */
    handleFeedback(type: string, row: any): void {
        this.currentOverrun = JSON.parse(JSON.stringify(row));
        this.visible = true;
    }

    /**
     * 新增录入事件回调函数
     */
    handleInitEventRecord(data: any): void {
        if (this.eventRecordType == 'add') {
            API.addEnter({ ...data, eventStatus: '1' })
                .then(() => {
                    this.yh_message_success('新增录入成功!');
                    this.paging.currentPage = 1;
                    super.getTableData();
                })
                .finally(() => {
                    this.eventRecordVisible = false;
                });
        } else if (this.eventRecordType == 'follow-manage') {
            // 跟踪记录;
            API.feedbackInsert({ ...data, feedbackType: '1' })
                .then(() => {
                    this.yh_message_success('新增跟踪记录成功!');
                    this.paging.currentPage = 1;
                    super.getTableData();
                })
                .finally(() => {
                    this.eventRecordVisible = false;
                });
        }
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 5px 2px;
    border: 1px solid #f2f2f2;
    margin-bottom: 10px;
}
.noOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 270px) !important;
    }
}
a {
    color: #578bec;
    padding: 0 5px;
}
.tag1,
.tag2,
.tag3 {
    color: #fff;
    width: 35px;
    text-align: center;
}
.tag1 {
    background-color: #e9d571;
    border-color: #e9d571;
}
.tag2 {
    background-color: #e98730;
    border-color: #e98730;
}
.tag3 {
    background-color: red;
    border-color: red;
}
</style>
